package com.shiguiwu.springmybatis.javabase.nio.lock;

import java.io.BufferedReader;
import java.io.FileReader;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @description:
 * @author: stone
 * @date: Created by 2021/11/10 14:55
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.nio.lock
 */
public class FileLockTests {

    public static void main(String[] args)throws Exception {
        ByteBuffer buffer = ByteBuffer.wrap("我是谁爱我".getBytes());

        Path path = Paths.get("E:\\1.txt");

        FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.APPEND);

        fileChannel.position(fileChannel.size() - 1);

        //加锁
        FileLock lock = fileChannel.lock();
        System.out.println("是否是共享锁" + lock.isShared());
        fileChannel.write(buffer);
        fileChannel.close();
        readFile("E:\\1.txt");
        //lock.release();
    }

    private static void readFile(String filePath) throws Exception {
        FileReader fileReader = new FileReader(filePath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String tr = bufferedReader.readLine();
        System.out.println("读取出内容：");
        while(tr != null) {
            System.out.println(" "+tr);
            tr = bufferedReader.readLine();
        }
        fileReader.close();
        bufferedReader.close();
    }

}
